package com.example.tys.baseapplication;

import android.Manifest;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.webkit.WebView;

import com.example.tys.baseapplication.Mvp.Presenter.PreparePresent;
import com.example.tys.baseapplication.Mvp.View.interfaces.IPrepareView;
import com.example.tys.baseapplication.NetModel.okhttp.OkHttpClientManger;

public class PrepareActivity extends BaseActivity<PreparePresent> implements IPrepareView {

    private WebView waitingWebView;
    //异步初始化完成
    private boolean initFinish;
    //动画（等待）时间到
    private boolean animFinish;
    //main是否已经显示
    private boolean isShowMain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_prepare);
        Debug.stopMethodTracing();
        asyncInit();
        initView();
        presenter.loadPrepareImg();

        requestPermission(null,
                Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
        );
    }

    private void asyncInit() {
        AsyncInit ex = new AsyncInit();
        ex.execute();
    }

    @Override
    protected void permissionGrant() {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                animFinish = true;
                startMainActivity();
            }
        }, 2000);
    }

    synchronized private void startMainActivity() {
        if (initFinish && animFinish) {
            if (!isShowMain) {
                isShowMain = true;
                Intent intent = new Intent(PrepareActivity.this, MainActivity.class);
                startActivity(intent);
                PrepareActivity.this.finish();
            }
        }
    }

    @Override
    protected void permissionsDenied() {
        super.permissionsDenied();
    }

    @Override
    PreparePresent createPresent() {
        return new PreparePresent(this);
    }

    private void initView() {
        waitingWebView = findViewById(R.id.pre_wv);
        waitingWebView.getSettings().setJavaScriptEnabled(true);
    }

    @Override
    public void setWaitingImg(String url) {
        waitingWebView.loadUrl(url);
    }


    final class AsyncInit extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            initFinish = false;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            initNet();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            initFinish = true;
            startMainActivity();
        }
    }


    private void initNet() {
    }

}
